<?php

	eb_include_class("EbSQLModel");

	class EbTableSQLModel extends EbSQLModel
	{
		var $primarykey;
		var $tablename;
		var $vomodulefile;
		
		public function __construct($tablename,$primarykey = null,$vomodulefile = null,$datasource = null)
		{						
			$this->tablename = $tablename;
			$this->primarykey = $primarykey;
			$this->vomodulefile = $vomodulefile;
						
			parent::__construct($datasource);
		}	
		
		public function getVO()
		{			
			return null;
		}

		public function getColumns()
		{
			throw new Exception('You must override the getColumns method in your model!');
		}

		public function select($fields = null,$where = null,$orderby = null)
		{
			$results = parent::select($this->tablename,$fields,$where,$orderby);
			
			if (!is_null($this->getVO()))
			{
				$buffer = array();
				
				foreach ($results AS $result)
				{
					$newVo = $this->getVO();
					
					foreach($result as $key => $value) 
					{
						$newVo->$key = $value;
					}
					
					$buffer []= $newVo;
				}
				
				return $buffer;
			}
			else
			{
				return $results;	
			}
		}
		
		public function __call($name, $arguments) 
		{
			$name = strtolower($name);
		
			if (strpos($name,'select') == 0)
			{
				$field = substr($name,8);
				$a = strrpos($field,'_');
								
				if ($a !== false)
				{					
					$limit = substr($field,$a+1);
					$field = substr($field,0,$a);	

					if (!is_numeric($limit))
					{
						$field = substr($name,8);
						$limit = 0;
					}					
				}
				else
				{
					$limit = 0;
				}

				if ($field === 'id')
				{
					$field = $this->primarykey;
					$limit = 1;
					
					$buffer = $this->select('*',"$field = ".$arguments[0]);
				}
				else
				{
					$buffer = $this->select('*',"$field = '".$arguments[0]."'");
				}
				
				if ($limit == 1)
				{
					return count($buffer) == 1 ? $buffer[0] : null;
				}
				else
				{
					return $buffer;
				}
			}
		}			
		
		public function insert($vo)
		{
			return parent::insert($this->tablename,$vo);
		}
		
		public function update($vo)
		{
			$key = $this->primarykey;
			
			return parent::update($this->tablename,$vo,$key.'='.$vo->$key);
		}		
		
		public function delete($vo)
		{
			$key = $this->primarykey;
			
			if (is_object($vo))
			{
				$vo = $vo->$key;	
			}
			
			return parent::delete($this->tablename,$key.'='.$vo);
		}
		
		public function create()
		{
			return parent::create($this->tablename, $this->getColumns());
		}
	}